package server

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
)

type HttpServer struct {
	Api        *echo.Echo
	controller *Controller
}

func MakeHTTPServer(rootPath string) *HttpServer {
	obs := &HttpServer{
		Api: echo.New(),
		controller: &Controller{
			RootPath: rootPath,
		},
	}
	obs.loggerInit()
	obs.routeInit()

	return obs
}

func (s *HttpServer) loggerInit() {
	s.Api.Use(middleware.Logger())
}

func (s *HttpServer) routeInit() {
	s.Api.GET("/object", s.controller.GetObject)
	s.Api.PUT("/object", s.controller.PutObject)
}

type Controller struct {
	RootPath string
}

func (h *Controller) GetObject(c echo.Context) error {
	return c.String(http.StatusOK, "Hello Wrold")
}

func (h *Controller) PutObject(c echo.Context) error {
	req := c.Request()

	reader, err := req.MultipartReader()
	if err != nil {
		c.String(http.StatusOK, "读取失败")
		return err
	}

	header := req.Header
	sha1 := header["Ifile-Sha1"][0]
	filePath := filepath.Join(h.RootPath, sha1)

	fp, err := os.OpenFile(filePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
	if err != nil {
		log.Fatalln(err)
	}
	defer fp.Close()

	for {
		part, err := reader.NextPart()
		if err == io.EOF {
			break
		}

		if part.FileName() != "" {
			io.Copy(fp, part)
		}
	}
	return c.HTML(http.StatusOK, fmt.Sprintf("<h2>传输完成</h2>"))
}
